<template>
    <el-card>
        <el-form :model="queryParams" ref="queryParams" :inline="true" label-width="100px">
            <el-form-item label="appID" prop="app">
                <el-input v-model="queryParams.app" placeholder="appID" size="small"></el-input>
            </el-form-item>
            <el-form-item label="应用名" prop="appName">
                <el-input v-model="queryParams.appName" placeholder="应用名" size="small"></el-input>
            </el-form-item>
             <el-form-item label="标签" prop="tagCondition">
                <el-input v-model="queryParams.tagCondition" placeholder="标签" size="small"></el-input>
            </el-form-item>
            <el-form-item label="认证方式" prop="authType">
                 <el-select v-model="queryParams.authType" placeholder="认证方式" size="small">
                    <el-option v-for="item in authTypeList" :label="item.label" :key="item.value" :value="item.value"></el-option>
                  </el-select>
            </el-form-item>
            <el-form-item >
                <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-delete" size="small" @click="resetQuery('queryParams')">清空</el-button>
            </el-form-item>
        </el-form>
        <el-row style="margin: 10px">
            <el-col :span="2">
                <el-button type="primary" icon="el-icon-plus" size="small" @click="handleAdd">新增</el-button>
            </el-col>
        </el-row>
        <el-table :data="tableData" border style="width: 100%" size="small">
            <el-table-column type="index" label="#" width="50"></el-table-column>
            <el-table-column label="appID" prop="app"></el-table-column>
            <el-table-column label="应用名" prop="appName"></el-table-column>
            <el-table-column label="标签" prop="tags">
                <template slot-scope="{row}">
                    {{row.tags|tagsFilter}}
                </template>
            </el-table-column>
            <el-table-column label="是否启用认证" prop="useAuth">
                <template slot-scope="{row}">
                    {{row.useAuth|useAuthFilter}}
                </template>
            </el-table-column>
            <el-table-column label="认证方式" prop="authType">
                 <template slot-scope="{row}">
                    {{row.useAuth|authTypeFilter}}
                </template>
            </el-table-column>
            <el-table-column label="是否启用IP白名单" prop="useWhiteList">
                 <template slot-scope="{row}">
                    {{row.useAuth|useWhiteFilter}}
                </template>
            </el-table-column>
            <el-table-column label="IP白名单" prop="authIps"></el-table-column>
            <el-table-column label="自定义配置" prop="customConfig"></el-table-column>
            <el-table-column label="操作" width="300" align="center">
                <template slot-scope="scope">
                    <el-button size="small" type="text" icon="el-icon-view" @click="handleView(scope.row)">查看</el-button>
                    <el-button size="small" type="text" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button size="small" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
                    <el-button size="small" type="text" icon="el-icon-s-operation" @click="handleRoute(scope.row)">路由权限</el-button>
                </template>
            </el-table-column>
        </el-table>
         <el-pagination
                v-show="total>0"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                background
                :current-page="1"
                :page-sizes="[10, 20, 30, 40,50,100]"
                :page-size="10"
                layout="total, sizes, prev, pager, next, jumper"
                class="pagination-container"
                :total="total">
         </el-pagination>
        <el-dialog :title="title" :visible.sync="formVisible" @close="resetForm('addForm')">
            <el-form :model="addForm" :rules="rules" ref="addForm" :disabled="isView">
                <el-form-item  prop="app" label="appId：" :label-width="formLabelWidth" required>
                    <el-input v-model="addForm.app" autocomplete="off" size="small" placeholder="请输入名称"></el-input>
                    <span class="tips">调用方通过请求头fizz-appid传递appid
                        <el-tooltip effect="dark" content="示例
                            fizz-appid: 10001
                            fizz-sign: e4502ba3a71448bbbcecef22b305d2ba
                            fizz-ts: 1605255335977" placement="top">
                            <el-button type="text">(示例)</el-button>
                        </el-tooltip>
                    </span>
                </el-form-item>
                <el-form-item  prop="appName" label="应用名：" :label-width="formLabelWidth" required>
                    <el-input v-model="addForm.appName" autocomplete="off" size="small" placeholder="请输入应用名"></el-input>
                </el-form-item>
                <el-form-item  prop="tags" label="标签" :label-width="formLabelWidth">
                    <el-tag :key="tag" v-for="tag in dynamicTags" closable :disable-transitions="false" @close="handleClose(tag)">
                        {{tag}}
                    </el-tag>
                    <el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput"
                        size="small"
                        @keyup.enter.native="handleInputConfirm"
                        @blur="handleInputConfirm"
                    >
                    </el-input>
                    <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 新标签</el-button>
                </el-form-item>
                <el-form-item  prop="useAuth" label="是否启用认证" :label-width="formLabelWidth">
                    <el-switch v-model="addForm.useAuth"></el-switch>
                </el-form-item>
                <el-row v-if="addForm.useAuth">
                    <el-col :span="12">
                        <el-form-item label="认证方式：" prop="authType" required :label-width="formLabelWidth">
                            <el-select v-model="addForm.authType" placeholder="认证方式" size="small">
                                <el-option v-for="item in authTypeList" :label="item.label" :key="item.value" :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20" v-if="addForm.useAuth">
                    <el-col :span="20">
                        <el-form-item label="密钥" prop="secretkey" :label-width="formLabelWidth" required>
                            <el-input type="text" v-model="addForm.secretkey" size="small" placeholder="请输入或生成密钥"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="2">
                        <el-button type="primary" size="small" @click="generatorScrect">生成随机密钥</el-button>
                    </el-col>
                </el-row>
                <el-form-item  prop="useWhiteList" label="是否启用IP白名单" :label-width="formLabelWidth">
                    <el-switch v-model="addForm.useWhiteList"></el-switch>
                </el-form-item>
                <el-form-item label="IP白名单" v-if="addForm.useWhiteList" :label-width="formLabelWidth" prop="authIps">
                    <el-input v-model="addForm.authIps" placeholder="多个IP或IP段用逗号,分隔" size="small" type="textarea" :rows="3"></el-input>
                    <div style="font-size:10px;opacity: .7;">IP段支持 1.2.3.100-120 和 1.2.3.*两种格式，仅最后一段可用范围或星号表示</div>
                </el-form-item>
                <el-form-item  prop="customConfig" label="自定义配置：" :label-width="formLabelWidth">
                    <el-input v-model="addForm.customConfig" type="textarea" rows="4" autocomplete="off" size="small" placeholder="请输入名称"></el-input>
                    <div class="tips">AppID级别的自定义配置供自定义插件使用，所有插件均可获取到此配置信息
                    <el-tooltip effect="dark" content="示例
                        fizz-appid: 10001
                        fizz-sign: e4502ba3a71448bbbcecef22b305d2ba
                        fizz-ts: 1605255335977" placement="top">
                        <el-button type="text">(插件示例)</el-button>
                    </el-tooltip>
                    </div>
                    </el-form-item>
            </el-form>
              <div slot="footer" class="dialog-footer" v-if="!isView">
                    <el-button type="primary" @click="handleSubmit('addForm')" size="small">保存</el-button>
                    <el-button @click="formVisible = false" size="small">取消</el-button>
               </div>
         </el-dialog>
         <el-dialog :title="`【${routeApp}】 路由权限`" :visible.sync="routeVisible">
              <el-row :gutter="10">
                <el-col :span="24">
                    <div style="margin-bottom: 10px">
                        <el-button type="primary" icon="el-icon-plus" size="small" @click="handleAddRoute">添加路由</el-button>
                        <el-button type="danger" plain icon="el-icon-delete" size="small" @click="handleDelete($refs.tableRef.selection)">批量删除</el-button>
                    </div>
                </el-col>
             </el-row>
            <el-tag style="width: 100%">
                <span>当前表格已选择 {{selectionList.length}}项</span> &nbsp;&nbsp;&nbsp;
                <el-button type="text">清空</el-button>
            </el-tag>
             <el-table :data="routeTableData" border style="width: 100%;margin-top: 10px" size="small" ref="routeTableRef" @selection-change="selectionChange">
                <el-table-column type="selection" label="#" width="55"></el-table-column>
                <el-table-column label="网关分组" prop="gatewayGroup">
                    <template slot-scope="{row}">
                        <span>{{ row.gatewayGroup | groupFilter(gatewayGroupList) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="路由类型" prop="proxyMode">
                    <template slot-scope="{row}">
                        <span v-if="row.proxyMode===1">服务编排</span>
                        <span v-if="row.proxyMode===2">服务发现</span>
                        <span v-if="row.proxyMode===3">反向代理</span>
                    </template>
                </el-table-column>
                <el-table-column label="前端服务名" prop="service"></el-table-column>
                <el-table-column label="前端API路径" prop="path"></el-table-column>
                <el-table-column label="请求方法" prop="method"></el-table-column>
                <el-table-column width="200" align="center" label="操作">
                    <template slot-scope="scope">
                        <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)">查看</el-button>
                        <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row.id)">删除</el-button>
                    </template>
                </el-table-column>
             </el-table>
             <el-pagination
                v-show="routeTotal>0"
                @size-change="handleRouteSizeChange"
                @current-change="handleRouteCurrentChange"
                background
                :current-page="1"
                :page-sizes="[10, 20, 30, 40,50,100]"
                :page-size="10"
                layout="total, sizes, prev, pager, next, jumper"
                class="pagination-container"
                :total="routeTotal">
           </el-pagination>
         </el-dialog>
         <el-drawer title="添加路由" :visible.sync="drawerVisible" direction="rtl" size="50%" :before-close="handleClose">
             <el-form :model="addRouteParams" ref="addRouteParams" label-width="120px">
                 <el-row>
                   <el-col :span="12">
                       <el-form-item label="网关分组" prop="gatewayGroup">
                           <el-select v-model="addRouteParams.gatewayGroup" placeholder="请选择" size="small" style="width: 100%">
                                <el-option v-for="item in gatewayGroupList" :key="item.groupId" :label="`${item.groupName}(${item.groupId})`" :value="item.groupId"></el-option>
                            </el-select>
                       </el-form-item>
                   </el-col>
                   <el-col :span="12">
                       <el-form-item label="前端服务名">
                           <el-input v-model="addRouteParams.service" placeholder="前端服务名" size="small"></el-input>
                       </el-form-item>
                   </el-col>
                 </el-row>
                 <el-row>
                   <el-col :span="12">
                        <el-form-item label="前端API路径" prop="path">
                           <el-input v-model="addRouteParams.path" placeholder="前端API路径" size="small"></el-input>
                       </el-form-item>
                   </el-col>
                   <el-col :span="12">
                       <el-form-item label="请求方法" prop="method">
                            <el-select v-model="addRouteParams.method" multiple collapse-tags placeholder="请选择" size="small">
                                <el-option v-for="item in methods" :key="item" :label="item" :value="item"></el-option>
                            </el-select>
                        </el-form-item>
                   </el-col>
                 </el-row>
                 <el-row>
                   <el-col :span="12">
                       <el-form-item label="访问" prop="access">
                             <el-select v-model="addRouteParams.access" placeholder="访问" size="small">
                                <el-option label="允许" value="a"></el-option>
                                <el-option label="禁止" value="f"></el-option>
                            </el-select>
                        </el-form-item>
                   </el-col>
                   <el-col :span="12">
                        <el-form-item >
                            <el-button type="primary" icon="el-icon-search" size="small" @click="handleRouteQuery">搜索</el-button>
                            <el-button icon="el-icon-delete" size="small" @click="resetRouteQuery('addRouteParams')">清空</el-button>
                        </el-form-item>
                   </el-col>
                 </el-row>
             </el-form>
             <el-row :gutter="10" style="padding: 10px">
                <el-col :span="24">
                    <div style="margin-bottom: 10px">
                        <el-button type="primary" icon="el-icon-plus" size="small" @click="handleAdd">新增</el-button>
                    </div>
                </el-col>
            </el-row>
            <el-tag style="width: 100%;">
                <span>当前表格已选择 {{selectionList.length}}项</span> &nbsp;&nbsp;&nbsp;
                <el-button type="text">清空</el-button>
            </el-tag>
             <el-table :data="routeTableData" border style="width: 100%;margin: 20px;" size="small" ref="routeTableRef" @selection-change="selectionChange">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column type="index" label="#" width="55"></el-table-column>
                <el-table-column label="网关分组" prop="gatewayGroup">
                    <template slot-scope="{row}">
                        <span>{{ row.gatewayGroup | groupFilter(gatewayGroupList) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="路由类型" prop="proxyMode">
                    <template slot-scope="{row}">
                        <span v-if="row.proxyMode===1">服务编排</span>
                        <span v-if="row.proxyMode===2">服务发现</span>
                        <span v-if="row.proxyMode===3">反向代理</span>
                    </template>
                </el-table-column>
                <el-table-column label="前端服务名" prop="service"></el-table-column>
                <el-table-column label="前端API路径" prop="path"></el-table-column>
                <el-table-column label="请求方法" prop="method"></el-table-column>
                <el-table-column label="访问" prop="discoveryMode"></el-table-column>
             </el-table>
             <el-pagination
                v-show="routeTotal>0"
                @size-change="handleRouteSizeChange"
                @current-change="handleRouteCurrentChange"
                background
                :current-page="1"
                :page-sizes="[10, 20, 30, 40,50,100]"
                :page-size="10"
                layout="total, sizes, prev, pager, next, jumper"
                class="pagination-container"
                :total="routeTotal">
           </el-pagination>
         </el-drawer>
         <el-dialog title="新增" width="30%">
             <el-form :model="addRouteForm" label-width="100px">
                 <el-row>
                   <el-col :span="12">
                        <el-form-item label="网关分组">
                            <el-select v-model="addRouteForm.gatewayGroup" placeholder="请选择" size="small" style="width: 100%">
                                <el-option v-for="item in gatewayGroupList" :key="item.groupId" :label="`${item.groupName}(${item.groupId})`" :value="item.groupId"></el-option>
                            </el-select>
                        </el-form-item>
                   </el-col>
                   <el-col :span="12">
                       <el-form-item label="路由类型">
                           <el-input v-model="addRouteForm.type" placeholder="路由类型" size="small"></el-input>
                       </el-form-item>
                   </el-col>
                 </el-row>
                 <el-row>
                   <el-col :span="12">
                        <el-form-item label="前端服务名" prop="service">
                           <el-input v-model="addRouteForm.service" placeholder="前端服务名" size="small"></el-input>
                       </el-form-item>
                   </el-col>
                   <el-col :span="12">
                        <el-form-item label="前端API路径" prop="path">
                           <el-input v-model="addRouteForm.path" placeholder="前端API路径" size="small"></el-input>
                       </el-form-item>
                   </el-col>
                 </el-row>
                 <el-row>
                   <el-col :span="12">
                        <el-form-item label="请求方法" prop="method">
                           <el-input v-model="addRouteForm.method" placeholder="请求方法" size="small"></el-input>
                       </el-form-item>
                   </el-col>
                   <el-col :span="12">
                        <el-form-item label="访问" prop="path">
                           <el-input v-model="addRouteForm.path" placeholder="访问" size="small"></el-input>
                       </el-form-item>
                   </el-col>
                 </el-row>
             </el-form>
         </el-dialog>
    </el-card>
</template>

<script>
import { getAppIdList,getUUID,save,getRouteData } from '@/api/proxy/appId.api'
import { getGroupList } from '@/api/callback/config.api.js'
    export default {
        data() {
            return {
                  tableData: [],
                  total: 0,
                  queryParams: {
                     current: 1,
                     size: 10,
                     app: undefined,
                     appName: undefined,
                     tagCondition: undefined,
                     authType: undefined
                  },
                  formLabelWidth: "130px",
                  title: '新增',
                  rules: {
                    app: [{ required: true, message: '请输入appID', trigger: 'blur' }],
                    appName: [{ required: true, message: '请输入应用名', trigger: 'blur' }],
                    authType: [{ required: true, message: '请选择认证方式', trigger: 'blur' }],
                    secretkey: [{ required: true, message: '请输入密钥', trigger: 'blur' }],
                  },
                  formVisible: false,
                  isView: false,
                  authTypeList: [
                      {label: 'MD5签名',value: 1},
                      {label: '密钥认证',value: 2},
                      {label: '自定义认证插件',value: 3},
                  ],
                  addForm: {},
                  inputVisible: false,
                  inputValue: '',
                  dynamicTags: [],
                  routeVisible: false,
                  routeTableData: [],
                  // 选中的数组
                  selectionList: [],
                  routeTotal: 0,
                  routeParams: {
                      current: 1,
                      size: 10
                  },
                  // 网关分组
                  gatewayGroupList: [],
                  routeApp: '',
                  drawerVisible: false,
                  addRouteParams: {
                      current: 1,
                      size: 10
                  },
                  methods: ['GET','POST','PUT','DELETE','PATCH','HEAD','OPTIONS','TRACE'],
                  currentRow: {},
                  addRouteForm: {}
            }
        },
        mounted() {
            this.getList();
             this.getGroupList();
        },
        filters: {
            useAuthFilter(value) {
                return value===0?'否':'是'
            },
            authTypeFilter(value) {
                if(value===1) {
                    return 'MD5签名';
                }else if(value===2) {
                    return '密钥认证';
                }else if(value===3) {
                    return '自定义认证插件';
                }
            },
            useWhiteFilter(value) {
                return value===0?'否':'是';
            },
            tagsFilter(value) {
                return value.toString();
            },
             groupFilter(value,gatewayGroupList) {
                return gatewayGroupList.find(item=>item.groupId===value).groupName
            }
        },
        methods: {
            async getList() {
                const result = await getAppIdList(this.queryParams);
                if(result.code === 200) {
                    this.tableData = result.data.records;
                    this.total = result.data.total
                }
            },
            async getRouteList() {
                const result = await getRouteData(this.routeParams);
                if(result.code === 200) {
                    this.routeTableData = result.data.records;
                    this.routeTotal = result.data.total
                }
            },
            async getAddRouteList() {
                const result = await getRouteData(this.addRouteParams);
                if(result.code === 200) {
                    this.routeTableData = result.data.records;
                    this.routeTotal = result.data.total
                }
            },
             showInput() {
                    this.inputVisible = true;
                 this.$nextTick(_ => {
                    this.$refs.saveTagInput.$refs.input.focus();
                });
            },
            handleInputConfirm() {
                let inputValue = this.inputValue;
                if (inputValue) {
                this.dynamicTags.push(inputValue);
                }
                this.inputVisible = false;
                this.inputValue = '';
            },
            handleClose(tag) {
                this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
            },
            handleAdd() {
                this.formVisible = true;
            },
            // 搜索
            handleQuery() {
                this.queryParams.current = 1;
                this.getList();
            },
            // 清空
            resetQuery(formName) {
                this.$refs[formName].resetFields();
                this.getList();
            },
            handleSizeChange(val) {
                this.queryParams.size = val;
                this.getList();
            },
            handleCurrentChange(val) {
                this.queryParams.current = val;
                this.getList();
            },
             // 搜索
            handleRouteQuery() {
                this.addRouteParams.current = 1;
                 if(this.addRouteParams.method.length > 0) {
                    this.addRouteParams.method = this.addRouteParams.method.join(',');
                }   
                this.getAddRouteList();
            },
            // 清空
            resetRouteQuery(formName) {
                this.$refs[formName].resetFields();
                this.getAddRouteList();
            },
            handleRouteSizeChange(val) {
                this.routeParams.size = val;
                this.getRouteList();
            },
            handleRouteCurrentChange(val) {
                this.routeParams.current = val;
                this.getRouteList();
            },
            // 生成密钥
            async generatorScrect() {
                const result = await getUUID();
                if(result.code === 200) {
                    this.addForm.secretkey = result.data;
                }
            },
            async getGroupList() {
                const result = await getGroupList();
                if(result.code === 200) {
                    this.gatewayGroupList = result.data;
                }
            },
            resetForm(formName) {
                this.$refs[formName].resetFields();
            },
            // 保存
            handleSubmit(formName) {
                this.$refs[formName].validate(async (valid) => {
                    if (valid) {
                        this.addForm.tags = this.dynamicTags;
                        this.addFormuseAuth?this.addForm.useAuth=1:this.addForm.useAuth=0;
                        this.addFormuseWhiteList?this.addForm.useWhiteList=1:this.addForm.useWhiteList=0;
                        const result = await save(this.addForm);
                        if(result.code===200) {
                            this.$message.success('保存成功');
                            this.formVisible=false;
                            this.getList();
                        }
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            // 路由权限
            handleRoute(row) {
                this.routeParams.appCondition = row.app;
                // this.routeParams.noAppCondition = row.appId;
                this.currentRow = row;
                this.getRouteList();
                this.routeVisible = true;
                this.routeApp = row.appName;
            },
            // selection选中的change事件
            selectionChange(val) {
                this.selectionList = val;
            },
            handleAddRoute() {
                this.drawerVisible = true;
                this.addRouteParams.noAppCondition = this.currentRow?.app;
                // this.routeParams.appCondition = '';
                this.getAddRouteList();
            }
        }
       
    }
</script>

<style lang="scss" scoped>
.pagination-container {
    padding: 10px;
    text-align: right;
}
 .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
  .tips {
    color: #999;
    font-size: 12px;
    line-height: normal;
    margin-top: 2px;
    display: inline; 
}
</style>